package com.thread.sample;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.concurrent.Callable;

public class FileAnalysorCallable implements Callable<AnalyseResult>  {

	private String fileName;
	private String keyword;
	
	public FileAnalysorCallable(String fileName, String keyword) {
		this.keyword = keyword;
		this.fileName = fileName;
	}
	
	@Override
	public AnalyseResult call() throws Exception {
		AnalyseResult ar = new AnalyseResult();
		
		System.out.println("Thread " + Thread.currentThread().getName() + " is working...");
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
		
		int keywordLineNumber = 0;
		
		String line = null;
		while ((line = reader.readLine()) != null) {
			
			if (line.indexOf(keyword) == -1)
				continue;
			
			keywordLineNumber += (line.split(keyword).length - 1);
			
			ar.getLines().add(line);
		}
		
		reader.close();
		
		ar.setKeyword(keyword);
		ar.setNumber(keywordLineNumber);
		System.out.println("Thread " + Thread.currentThread().getName() + " finished.");
		return ar;
	}

}
